package falcon.server.processor;

import falcon.common.FalconConfig;
import falcon.common.Log;
import falcon.common.TextFile;
import falcon.script.FalconLangGlobal;
import falcon.script.FalconLangScript;
import falcon.server.FalconProManager;

public final class FalconFlowProcessor {
	
	public static boolean init(FalconConfig config) {
		if (s_global != null) {
			Log.log("init alreadly");
			return false;
		}
		String dir = config.getDir();
		if (dir == null || dir.isEmpty()) {
			Log.log("dir not found");
			return false;
		}
		if (dir.charAt(dir.length() - 1) != '/') {
			dir += '/';
		}
		String name = "flow.conf";
		String path = dir + name;
		String[] lines = TextFile.readLines(path);
		if (lines == null) {
			Log.log("read conf failure;path=%s", path);
			return false;
		}
		s_global = new FalconLangGlobal();
		for (int i = 0; i < lines.length; i ++) {
			String line = lines[i];
			String[] array = line.split(" ");
			if (array.length != 2) {
				Log.log("parse line in %s failure;path=%s;line=%s", name, path, line);
				return false;
			}
			String key = array[0];
			String value = array[1];
			s_global.bindFlow(key, value);
		}
		return true;
	}

	public static void processExec(FalconProManager manager, FalconProManager.Req req, String[] pa) {
		String name = pa[0];
		String parameter = pa[1];
		String[] args = null;
		if (!parameter.isEmpty()) {
			args = parameter.split("\n");
		}
		FalconLangScript script = new FalconLangScript(s_global, name, args);
		int errno = script.execute();
		req.desc = "";
		req.errno = errno;
	}
	
	private static FalconLangGlobal s_global = null;
}
